<!-- 班级学生级联选择器  -->
<template>
  <el-cascader
    ref="cascaderRef"
    class="!max-w-220px !w-fit"
    v-model="cascaderValue"
    :options="classList"
    :props="baseCascaderProps"
    :clearable="clearable"
    filterable
    :placeholder="placeholder"
    @change="cascaderChange"
    @clear="cascaderChange([])"
  />
</template>
<script setup lang="ts">
import { ClassesApi } from '@/api/school/classes'
import { StudentApi } from '@/api/school/student'
import { defaultProps } from '@/utils/tree'

// 定义组件名称
defineOptions({ name: 'ClassStudentCascader' })

const props = defineProps({
  placeholder: {
    type: String,
    default: '全部'
  },
  cascaderProps: {
    type: Object,
    default: () => {
      return {}
    }
  },
  clearable: {
    type: Boolean,
    default: false
  },
  // 是否自动设置默认值 1:园区 2: 班级 true/3: 学生
  autoDefaultValue: {
    type: [Boolean, Number],
    default: 1
  }
})

const emit = defineEmits(['change'])
const classList: any = ref([]) //班级列表
const cascaderRef = ref()
const cascaderValue: any = ref([])
// 级联选择器属性
const baseCascaderProps: any = computed(() => ({
  ...defaultProps,
  lazy: true,
  emitPath: true,
  checkStrictly: true, // 父子节点不关联
  checkOnClickNode: false, // 点击节点时是否选中或取消选中该节点
  lazyLoad: async (node, resolve) => {
    const { level, data } = node
    // 二级节点（学生）需要懒加载
    if (level === 2) {
      try {
        const list = await StudentApi.getSimpleStudentList(data.id)
        list.forEach((item) => {
          item.id = item.id
          item.name = item.studentName
          item.leaf = true
        })
        resolve(list)
      } catch (e) {
        console.error(e)
        resolve([])
      }
    } else {
      resolve([])
    }
  },
  ...props.cascaderProps
}))

const setDefaultValue = async () => {
  if (!classList?.value?.length) {
    return
  }
  let curClassItem: any = null
  let curStudentItem: any = null
  let pathLabels: any = []
  const curSchoolItem: any = classList.value?.find(async (item) => {
    if (props.autoDefaultValue === 1) {
      cascaderValue.value = [item.id]
      pathLabels = [item.name]
      cascaderChange(cascaderValue.value, pathLabels)
      return item.id
    }
    curClassItem = item.children.find((subItem) => subItem.hasOwnProperty('id'))
    if (props.autoDefaultValue === 2) {
      cascaderValue.value = [item.id, curClassItem.id]
      pathLabels = [item.name, curClassItem.name]
      cascaderChange(cascaderValue.value, pathLabels)
      return curClassItem
    }
    const curStudentList = await StudentApi.getSimpleStudentList(curClassItem.id)
    if (curStudentList?.length) {
      curStudentItem = curStudentList.find((subItem) => subItem.hasOwnProperty('id'))
    }
    if (curStudentItem) {
      cascaderValue.value = [curSchoolItem.id, curClassItem.id, curStudentItem.id]
      pathLabels = [curSchoolItem.name, curClassItem.name, curStudentItem.name]
      cascaderChange(cascaderValue.value, pathLabels)
    }
    return curStudentItem
  })
}
const getFilterData = async () => {
  classList.value = await ClassesApi.getClassesList()
  classList.value.forEach((item: any) => {
    if (item?.name?.includes('景秀')) {
      item.id = 'jingxiu'
    } else {
      item.id = 'yuanhu'
    }
  })
  if (props.autoDefaultValue) {
    setDefaultValue()
  }
}
const cascaderChange = async (value, pathLabels = []) => {
  const queryParams: any = {}
  if (value?.length) {
    queryParams.schoolCode = value[0]
    queryParams.classId = value[1]
    queryParams.studentId = value[2]
  }
  cascaderRef.value.togglePopperVisible(false)
  // 选中的节点label
  const checkedNode = cascaderRef.value.getCheckedNodes()?.[0]
  emit('change', queryParams, checkedNode?.pathLabels || pathLabels)
}
onMounted(() => {
  getFilterData()
})
</script>
<style lang="scss" scoped></style>
